package com.wei.web.middleware.retry.compensate.reach;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tuya.basic.client.util.http.TuyaHttpClient;
import com.tuya.biz.platform.framework.compensate.config.CompensateConfig;
import com.tuya.biz.platform.framework.config.EnvironmentContext;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * 企业微信推送
 *
 * @author shihuimiao
 * create time: 下午4:52
 */
@Slf4j
public class WxBot implements Reach {

    private final String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=";

    private final String key;

    public WxBot(CompensateConfig config) {
        this.key = config.getWsBotKey();
    }

    @Override
    public void send(String content) {
        if (StringUtils.isBlank(key)) {
            return;
        }

        MarkdownTemplate template = new MarkdownTemplate();
        template.setContent(content);
        template.setWebHookUrl(url + key);

        List<Header> headers = Lists.newArrayList(new BasicHeader("Tuya-Intranet", "Tuya@intranet@2018"), new BasicHeader("Content-Type", "application/json;charset=UTF-8"));

        String api = "/api/notice/webhook/call";
        if (EnvironmentContext.isDaily()) {
            api = "http://basic.tuya-in.net" + api;
        } else if (EnvironmentContext.isPre()) {
            api = "http://basic-pre.tuya-in.net" + api;
        } else if (EnvironmentContext.isProd()) {
            api = "http://basic.tuya-in.net" + api;
        } else {
            log.warn("environment warn " + EnvironmentContext.getEnv());
            return;
        }

        Map<String, String> ret = TuyaHttpClient.getInstance().doPostV2(api, null, JSONObject.toJSONString(template),
                headers,
                UTF_8, null);

        log.info("post result = {}", ret);
    }

    @Setter
    @Getter
    @Accessors(chain = true)
    @ToString
    public static class MarkdownContent implements Serializable {
        private static final long serialVersionUID = 1L;

        private String content;
    }

    @Setter
    @Getter
    @Accessors(chain = true)
    @ToString
    public static class MarkdownTemplate implements Serializable {
        private static final long serialVersionUID = 1L;

        private String webHookUrl;

        private String msgType = "markdown";

        private String content;
    }

}
